﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Mysoft.Tasks.Queue.IService;
using Mysoft.Tasks.Queue.IService.IEvents;
using Mysoft.Tasks.Queue.RabbitMQ;
using Mysoft.Tasks.Queue.RabbitMQ.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mysoft.Tasks.Queue.RedisMQ.Extensions
{
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 添加RedisMQEventBus
        /// </summary>
        /// <returns></returns>
        public static IServiceCollection AddRedisMQEventBus(this IServiceCollection services)
        {
            services.TryAddSingleton<IMQEventBus, RedisMQEventBus>();
            foreach (Type mType in typeof(IEvent).GetAssemblies())
            {
                services.TryAddSingleton(mType);
                foreach (Type hType in typeof(IEventHandler<>).GetMakeGenericType(mType))
                {
                    services.TryAddSingleton(hType);
                }
            }
            return services;
        }
        /// <summary>
        /// 自动订阅
        /// </summary>
        /// <param name="app"></param>
        public static void RedisMQEventBusAutoSubscribe(this IServiceProvider sp)
        {
            IMQEventBus eventBus = sp.GetRequiredService<IMQEventBus>();
            ILogger<IMQEventBus> logger = sp.GetRequiredService<ILogger<IMQEventBus>>();
            using (logger.BeginScope("EventBus Subscribe"))
            {
                logger.LogInformation($"================================RedisMQ订阅=======================================");
                foreach (Type mType in typeof(IEvent).GetAssemblies())
                {
                    var handlesAny = typeof(IEventHandler<>).GetMakeGenericType(mType);
                    if (handlesAny.Any())
                    {

                        logger.LogInformation($"{mType.Name}\t=>\t{string.Join("、", handlesAny)}");
                        eventBus.Subscribe(mType);
                    }
                }
                logger.LogInformation($"================================RedisMQ订阅=======================================");
            }
        }
     }
}
